/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.marlboroug.orders;

import com.marlboroug.entity.Orders;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;


@Stateless
public class OrdersManager implements OrdersManagerRemote {
    
    @PersistenceContext(unitName = "Marlboroug-ejbPU")
    EntityManager em;
    

    /** Permet de retourner un objet Orders en fonction d'un ID
     * 
     * @param ID_orders Un ID d'une commande
     * @return Un objet order
     */
    @Override
    public Orders find (Long ID_orders) {
        Orders order = em.find(Orders.class, ID_orders);
        return order;
    }

    /** Permet de mettre à jour une commande
     * 
     * @param order Envoie un objet order
     * @return Un boolean pour confirmer la modification
     */
    @Override
    public boolean update (Orders order) {
        Orders temp = find(order.getIDorders());
        if(temp != null){
            em.merge(order);
            return true;
        }else {
            return false;
        }
    }
    
    /** Permet de retourner une liste des 20 dernières commandes
     * 
     * @return Une liste des commandes
     */
    @Override
    public List<Orders> findOrdersIndex () {
        String q = "SELECT m FROM Orders m ORDER BY m.date_received DESC"; //"SELECT * FROM Orders ORDER BY orders.date  DESC LIMIT 20"
        TypedQuery<Orders> query = em.createQuery(q, Orders.class);
        query.setMaxResults(20);
        List<Orders> orders = query.getResultList();
        return orders;
    }
    
    /** Permet de retourner une liste des commandes
     * 
     * @return Une liste des commandes
     */
    @Override
    public List<Orders> findAll () {
        String q = "SELECT m FROM Orders m";
        TypedQuery<Orders> query = em.createQuery(q, Orders.class);
        List<Orders> orders = query.getResultList();
        return orders;
    }
    
}
